<template>
  <section>
    <el-card class="search-card">
      <BasicTableForm ref="formData"
        isScalingBtn
        :colNumOfRow="4"
        :formColumns="formItemList"
        :dataSource="formData"
        :defaultExpandStatus="false"
        :handleSearchForm="handleQueryForm" />
    </el-card>
    <el-card class="table-card">
      <basic-table
        showActionCol
        :showSelectCol="false"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :tableHeight="460"
        :actionColWidth="200"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange">
        <div slot="content_context">
          <el-button
            v-if="showBtn('导出') && supplierExportConfig.supervision"
            :disabled="!pagination.total"
            size="mini"
            type="primary"
            :loading="exporting"
            @click="handleExportFile"
            >导出</el-button>
        </div>
      </basic-table>
    </el-card>
  </section>
</template>

<script>
import { mapGetters, mapMutations, mapState } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
import BasicTableForm from '@/components/supplier/BasicForm'; // 表单组件
import BasicTable from '@/components/supplier/BasicTable';
import BaseList from '@/mixins/supplier/baseList';
import {
  querySupervisionApprovalListService,
  deleteSupervisionApprovalService,
  exportSupervisionApprovalListService,
  getSupervisionRegularPriceItemService,
  getSupervisionTempPriceItemService,
} from '@/api/supplier/supervision/approval';
import {
  getWorkflowJumpUrl,
  retrieveWorkflow,
} from '@/api/supplier/workflow';
import { createExcelByExport } from '@/utils/bizUtils';
import { getHasIndexTableData } from '@/pages/supplier/utils/bizUtils';
import { INITIAL_FIELDS_VALUE, FORM_ITEM_LIST, TABLE_COLUMNS } from './constants';

export default {
  mixins: [ BaseList ],
  components: {
    BasicTableForm,
    BasicTable,
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    ...mapState('supplier/priceItem', [ 'priceItem' ]),
  },
  data () {
    return {
      formItemList: FORM_ITEM_LIST,
      tableInfo: {
        list: [],
        selection: [],
        columns: TABLE_COLUMNS,
        loading: false
      },
      pagination: {
        current: 1,
        total: 0,
        size: 10
      },
      formData: Object.assign({}, INITIAL_FIELDS_VALUE),
      exporting: false
    };
  },
  created () {
    sessionStorage.setItem('buttonId', getBtnsId('查询'));
    this.getTableData();
  },
  methods: {
    ...mapMutations('supplier/priceItem', [
      'setPriceItem',
    ]),
    handleExportFile () {
      this.exporting = true
      exportSupervisionApprovalListService(this.getRequestParams()).then((res) => {
        createExcelByExport({ excelTitle: '核查审批跟进表', res })
        this.exporting = false
      }).catch((reason) => {
        console.log('reason', reason)
        this.exporting = false
      })
    },
    handleQueryForm () {
      this.getTableData(1);
    },
    // 页码切换
    handlePageChange (val) {
      this.getTableData(val);
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.getTableData(1, val);
    },
    // 获取列表查询参数
    getRequestParams () {
      const {
        supplierCode,
        supplierName,
        status,
        documentType,
        sponsor,
        launchTime: [ launchStartTime, launchEndTime ],
      } = this.formData
      return {
        supplierCode,
        supplierName,
        status,
        documentType,
        sponsor,
        launchStartTime,
        launchEndTime,
      }
    },
    async getTableData (current = this.pagination.current, size = this.pagination.size) {
      this.tableInfo.loading = true
      const params = Object.assign({ current, size }, this.getRequestParams())
      const resp = await querySupervisionApprovalListService(params)
      this.tableInfo.loading = false
      if (resp && resp.result) {
        const { records, total, pages } = resp.result
        this.pagination = Object.assign(this.pagination, { current, size, total, pages })
        this.tableInfo.list = getHasIndexTableData(records, this.pagination)
        this.setFormItemData && this.setFormItemData(Object.assign({}, params, this.pagination))
      } else {
        this.tableInfo.list = []
      }
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      // status 1: 待提交 10:待审批 20:审批通过 30:审批驳回
      const { id, requestId, status } = row
      const renderByStatus = () => {
        switch (status) {
          case 1:
          case 40:
            return <div>
              <el-button type="text" disabled={!this.showBtn('编辑')} nativeOnClick={() => { this.handleEdit(row) }}>编辑</el-button>
              <el-button type="text" disabled={!this.showBtn('删除')} nativeOnClick={() => { this.handleDelete(id) }}>删除</el-button>
            </div>;
          case 10:
            return <div>
              <el-button type="text" disabled={!this.showBtn('查看')} nativeOnClick={() => { this.handleView(row) }}>查看</el-button>
              {requestId ? <el-button type="text" disabled={!this.showBtn('审批流')} nativeOnClick={() => { this.handleViewApprovalFlow(requestId) }}>审批流</el-button> : null}
              {requestId ? <el-button type="text" disabled={!this.showBtn('取回')} nativeOnClick={() => { this.handleWithdraw(row) }}>取回</el-button> : null}
            </div>;
          case 20:
            return <div>
              <el-button type="text" disabled={!this.showBtn('查看')} nativeOnClick={() => { this.handleView(row) }}>查看</el-button>
              {requestId ? <el-button type="text" disabled={!this.showBtn('审批流')} nativeOnClick={() => { this.handleViewApprovalFlow(requestId) }}>审批流</el-button> : null}
            </div>;
          case 30:
            return <div>
              <el-button type="text" disabled={!this.showBtn('编辑')} nativeOnClick={() => { this.handleEdit(row) }}>编辑</el-button>
              {requestId ? <el-button type="text" disabled={!this.showBtn('审批流')} nativeOnClick={() => { this.handleViewApprovalFlow(requestId) }}>审批流</el-button> : null}
              <el-button type="text" disabled={!this.showBtn('删除')} nativeOnClick={() => { this.handleDelete(id) }}>删除</el-button>
            </div>;
          default:
            return <div></div>;
        }
      }
      return renderByStatus()
    },
    // 编辑
    async handleEdit (row) {
      // status 1: 待提交 40: 已取回
      // documentType 21: 正常价格核查  22: 临采价格核查
      const { id, documentType } = row
      this.tableInfo.loading = true
      let resp

      this.setPriceItem(null)
      if (documentType === 21) {
        // 获取正常价格核查详情
        resp = await getSupervisionRegularPriceItemService({ id })
      }
      if (documentType === 22) {
        // 获取临采价格核查详情
        resp = await getSupervisionTempPriceItemService({ id })
      }
      this.tableInfo.loading = false
      if (resp && resp.result) {
        this.setPriceItem(resp.result)
      }
      if (this.priceItem && this.priceItem.item && this.priceItem.item.id) {
        const jumpName = { 21: 'editRegularPriceSupervision', 22: 'editTempPriceSupervision' }[documentType]
        this.$router.push({ name: jumpName, query: { processId: id, } });
      } else {
        this.$message.error('数据异常')
      }
    },
    // 查看
    async handleView (row) {
      // status 10:待审批 20:审批通过
      // documentType 21: 正常价格核查  22: 临采价格核查
      const { id, documentType } = row
      // console.log('handleView :>> ', row);
      this.tableInfo.loading = true
      let resp

      this.setPriceItem(null)
      if (documentType === 21) {
        // 获取正常价格核查详情
        resp = await getSupervisionRegularPriceItemService({ id })
      }
      if (documentType === 22) {
        // 获取临采价格核查详情
        resp = await getSupervisionTempPriceItemService({ id })
      }
      this.tableInfo.loading = false
      if (resp && resp.result) {
        this.setPriceItem(resp.result)
      }
      if (this.priceItem && this.priceItem.item && this.priceItem.item.id) {
        const jumpName = { 21: 'viewRegularPriceSupervision', 22: 'viewTempPriceSupervision' }[documentType]
        this.$router.push({ name: jumpName, query: { processId: id, } });
      } else {
        this.$message.error('数据异常')
      }
    },
    // 删除
    handleDelete (id) {
      this.$confirm('确定要删除暂存吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableInfo.loading = true
        deleteSupervisionApprovalService(id).then(() => {
          this.tableInfo.loading = false
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getTableData()
        }).catch(() => {
          this.tableInfo.loading = false
        });
      }).catch(() => {});
    },
    // 查看审批流
    handleViewApprovalFlow (requestId) {
      // 动态获取工作流跳转地址
      getWorkflowJumpUrl({ requestId }).then(({ result }) => {
        window.open(result, '_blank')
      })
    },
    // 取回单据
    handleWithdraw ({ requestId: oaRequestId, createUserId: itemUserId }) {
      this.$confirm('确定要取回当前单据吗?', '取回', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableInfo.loading = true
        retrieveWorkflow({ oaRequestId, itemUserId })
          .then(({ result }) => {
            this.tableInfo.loading = false
            this.$message({
              type: 'success',
              message: '取回成功!'
            });
            this.getTableData()
          }).catch(() => {
            this.tableInfo.loading = false
          });
      }).catch(() => {});
    },
  },
}
</script>
